// fileName      :  reids.go
// createdAt     :  2021-10-11
// description   :

package redis

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"go.uber.org/zap"
	"log"
	"time"
	"zl-gin/config"
	"zl-gin/utils"
)

var rds *redis.Client

func InitRedis() {
	log.Println("init redis...")
	conf := config.Get().Redis
	// 初始化连接
	rds = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", conf.Host, conf.Port),
		Password: conf.Password, // no password set
		DB:       conf.Db,       // use default DB
		PoolSize: conf.PollSize, // 连接池大小
	})

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	_, err := rds.Ping(ctx).Result()
	if err != nil {
		log.Panicf("init redis failed, error : %v\n", err)
	}
}

type Hook struct {
}

func (h *Hook) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
	zap.L().Info("redis beforeProcess hook", zap.String("traceId", utils.GlobalTrace.TraceId), zap.String("cmd",fmt.Sprintf("%s",cmd)))
	return ctx, nil
}

func (h *Hook) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
	zap.L().Info("redis afterProcess hook ", zap.String("traceId", utils.GlobalTrace.TraceId), zap.String("cmd",fmt.Sprintf("%s",cmd)))
	return nil
}

func (h *Hook) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
	zap.L().Info("redis beforeProcessPipeline hook", zap.String("traceId", utils.GlobalTrace.TraceId), zap.String("cmd",fmt.Sprintf("%s",cmds)))
	return ctx, nil
}

func (h *Hook) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
	zap.L().Info("redis afterProcessPipeline hook", zap.String("traceId", utils.GlobalTrace.TraceId), zap.String("cmd",fmt.Sprintf("%s",cmds)))
	return nil
}

func GetInstance() *redis.Client {
	zap.L().Info("get Redis instance ", zap.String("traceId", utils.GlobalTrace.TraceId))

	hook := &Hook{}
	rds.AddHook(hook)

	return rds
}
